<template>

  <div id = "teamPage">
    <van-search v-model="searchText" placeholder="搜索队伍" clearable="true" @search="onSearch"/>

    <van-tabs v-model:active="active" @change="onTabChange">
      <van-tab title="公开" name="public"/>
      <van-tab title="加密" name="private"/>
      <van-tab title="我的" name="myjoin"/>
    </van-tabs>

    <van-button class="add-button" icon="plus" type="primary" @click="toAddTeam"/>
    <team-card-list :team-list="teamList"/>
    <van-empty v-if="teamList.length < 1" description="数据为空"/>
  </div>

</template>

<script setup>


import {useRouter} from "vue-router";
import TeamCardList from "../components/TeamCardList.vue";
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showFailToast} from "vant";
import {getCurrentUser} from "../services/user.ts";

const router = useRouter();
const searchText  = ref('');
const active = ref('public');
const loginUser = ref();
const toAddTeam =() =>{
  router.push({
    path: "/team/add"
  })
}


let tabTame = ref('');
const onTabChange =(name) =>{
  //console.log("active:",active)

  //console.log("name:",name)

  tabTame =  name;
  //console.log("tabTame1:",tabTame)
  //查公开
  if(name === 'public'){

    listTeam(searchText.value,0);
  }else if(name === 'private'){
    //查加密
    listTeam(searchText.value,2);
  } else if(name === 'myjoin'){
    //查所有
    myJoinlistTeams(searchText.value);
  }
}




const teamList  = ref([]);

onMounted(async() => {
  listTeam();
   loginUser.value = await getCurrentUser();
})

const onSearch = (val) =>{
  if(active.value === "public"){
    listTeam(val);
  }
  else if(active.value === "private"){
    listTeam(val,2);
  }
  else if(active.value === "myjoin"){
    myJoinlistTeams(val);
  }


}

/**
 * 搜索队伍
 * @param val
 * @returns {Promise<void>}
 */
const listTeam = async (val = '',status=0) => {
  //console.log("tabTame:",name);
    const res = await myAxios.get("/team/list", {
      params: {
        searchText: val,
        pageNum: 1,
        status,
      },
    });
  if (res?.code === 0) {
    teamList.value = res.data;
  } else {
    showFailToast('加载队伍失败，请刷新重试');
  }
}

/**
 * 搜索我加入的队伍
 * @param val
 * @returns {Promise<void>}
 */
const myJoinlistTeams = async (val = '') => {
  //console.log("tabTame:",name);
  const res = await myAxios.get("/team/list/join", {
    params: {
      searchText: val,
      pageNum: 1,
      userId: loginUser.value.id,
    },
  });
  if (res?.code === 0) {
    teamList.value = res.data;
  } else {
    showFailToast('加载队伍失败，请刷新重试');
  }
}




</script>

<style scoped>
@import "../assets/css/team.css";
</style>